package org.bdware.registry.webService.controller;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import org.apache.log4j.Logger;
import org.bdware.bdoa.authentication.annotation.AuthRequired;
import org.bdware.bdoa.authentication.utils.JwtContext;
import org.bdware.doip.core.model.digitalObject.DigitalObject;
import org.bdware.doip.core.model.metadata.MetaDO;
import org.bdware.doip.core.utils.DoipGson;
import org.bdware.registry.webService.model.ResponseWrapper;
import org.bdware.registry.webService.service.MetaDOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 数字对象元数据管理模块
 */
@RestController
@RequestMapping("/doa/reg/metado")
public class MetaDOController {
    Logger logger = Logger.getLogger(MetaDOController.class);

    @Autowired
    private MetaDOService doService;

    @RequestMapping("")
    public String index() {
        List<String> indexStr = new ArrayList<>();
        indexStr.add("/getDetailByID");
        indexStr.add("/getByUser");
        indexStr.add("/getAllGroupByUser");
        indexStr.add("/create");
        indexStr.add("/delete");
        indexStr.add("/search");
        return new Gson().toJson(indexStr);
    }

    /*
        url:http://127.0.0.1:8080/metaDO/getdetailbyid
        post,参数doID
        返回JSon格式的数字对象字符串
     */
    @RequestMapping("/getDetailByID")
    public ResponseWrapper getByID(@RequestParam("doID") String doID) {
        logger.debug("DO ID: " + doID);
        DigitalObject digitalObject = doService.getDOByID(doID);
        if (digitalObject == null) return new ResponseWrapper("{}");
        logger.debug("DO String: " + digitalObject.toString());
        return new ResponseWrapper(digitalObject.toString());
    }

    /*
        url:http://127.0.0.1:8080/metaDO/getbyuser
        post,参数userID
        返回JSon格式的数字对象字符串
     */
    @RequestMapping("getByUser")
    public ResponseWrapper getListByUserID(){
        String userID = (String) JwtContext.get("doi");
        if(userID == null) userID = "anonymous";
        System.out.println(userID);
        JsonArray doList = doService.getDOListByUserID(userID);

        if(doList == null)
            return new ResponseWrapper("[]");
        return new ResponseWrapper(new Gson().toJson(doList));
    }

    /*
        url:http://127.0.0.1:8080/metaDO/getallgroupbyuser
        get, 无参数
        返回JSon格式的数字对象字符串
     */
    @RequestMapping("/getAllGroupByUser")
    public ResponseWrapper getAllGroupByUserID() {
        HashMap<String, JsonArray> doList = doService.getAllDOListGroupByUserID();
        return new ResponseWrapper(new Gson().toJson(doList));
    }

    /*
       url:http://127.0.0.1:8080/metaDO/getHottest
       post,参数size
       返回访问次数最多的1前100个MetaDO的ID以及其Title
    */
    @RequestMapping("getHottest")
    public ResponseWrapper getHottest(@RequestParam("size") String size) {
        return new ResponseWrapper(doService.getHottestMetaDO(Integer.parseInt(size)));
    }

    /*
        url:http://127.0.0.1:8080/metaDO/create
        post, 参数为Json格式的DO字符串，id不可为空，参考格式
        {
            "id": "86.5000.470/do.hello",
            "type": "0.TYPE/DO.Metadata",
            "attributes": {
                "metadata": {
                    "标题": "柳熠发推：什么时候由媒体来宣布下任总统了？",
                    "来源": "环球网",
                    "分类": "新闻"
                }
            }
        }
     */
    @RequestMapping("create")
    @AuthRequired(required = true)
    public ResponseWrapper createDigitalObject(@RequestBody String doString){
        String userID = (String)JwtContext.get("doi");
        if(userID == null) userID = "anonymous";
        DigitalObject digitalObject = DoipGson.getDoipGson().fromJson(doString,DigitalObject.class);
        MetaDO metaDO = MetaDO.fromDO(digitalObject);
        if (metaDO == null) return new ResponseWrapper("unable to get metaDO from JSON string");
        logger.debug(metaDO.toString());
        return new ResponseWrapper(doService.storeDO(metaDO, userID));
    }


    @RequestMapping("update")
    @AuthRequired(required = true)
    public ResponseWrapper updateDigitalObject(@RequestBody String doString){
        String userID = (String)JwtContext.get("doi");
        if(userID == null) userID = "anonymous";
        DigitalObject digitalObject = DoipGson.getDoipGson().fromJson(doString,DigitalObject.class);
        MetaDO metaDO = MetaDO.fromDO(digitalObject);
        if (metaDO == null) return new ResponseWrapper("unable to get metaDO from JSON string");
        logger.debug(metaDO.toString());
        return new ResponseWrapper(doService.updateDO(metaDO, userID));
    }

    /*
        url:http://127.0.0.1:8080/metaDO/delete
        post,参数doID
        返回JSon格式的数字对象字符串
     */
    @RequestMapping("delete")
    @AuthRequired(required = true)
    public ResponseWrapper deleteDigitalObject(@RequestParam("doID") String doID){
        String userID = (String)JwtContext.get("doi");
        if(userID == null) userID = "anonymous";
        if(doService.deleteDOByID(doID,userID))
            return new ResponseWrapper("success");
        else
            return new ResponseWrapper("failed");
    }


    /*
        url:http://127.0.0.1:8080/metaDO/search
        post,参数query
        返回100条搜索匹配的结果，每条结果包含所有元数据
     */
    @RequestMapping("search")
    public ResponseWrapper search(@RequestParam("query") String query) {
        return new ResponseWrapper(doService.search(query, 100));
    }

    /*
    返回registry的统计信息
     */
    @RequestMapping(value = "/getStat", method = RequestMethod.GET)
    public ResponseWrapper getStat(){
        return new ResponseWrapper<>(doService.getStat());
    }

}
